#!/bin/sh

SNAPPER_CONFIGS_FILE="/etc/snapper/snapper"
SNAPPER_CONFIG_APK_SNAP_ITEM="root-apk-snap"

# Check if /etc/snapper/snapper exists, add call to config for apk-snap
if [ -f "$SNAPPER_CONFIGS_FILE" ]; then
    # Extract the value of SNAPPER_CONFIGS from the file
    SNAPPER_CONFIGS=$(awk -F'[:"]+' '/^SNAPPER_CONFIGS=/ {print $3}' "$SNAPPER_CONFIGS_FILE")

    # Check if "root-apk-snap" is in the SNAPPER_CONFIGS
    if [ -n "$SNAPPER_CONFIGS" ] && echo "$SNAPPER_CONFIGS" | grep -qw "$SNAPPER_CONFIG_APK_SNAP_ITEM"; then
        SNAPPER_CONFIGS=$(echo "$SNAPPER_CONFIGS" | sed "s/\b$DEFAULT_SNAPPER_ITEM\b//g" | sed 's/  / /g' | sed 's/^ //;s/ $//')
        sed -i "/^SNAPPER_CONFIGS=/s/=.*/=\"$SNAPPER_CONFIGS\"/" "$SNAPPER_CONFIGS_FILE"
        echo "$SNAPPER_CONFIG_APK_SNAP_ITEM removed from SNAPPER_CONFIGS: $SNAPPER_CONFIGS"
    fi
else
    echo "Snapper not properly installed, $SNAPPER_CONFIGS_FILE does not exist"
fi


# Check if snapper config for apk-snap, and snapshots subvol exists; and take appropriate action
if [ -f "/etc/snapper/configs/root-apk-snap" ]  && [ -d "/.snapshots" ]; then
    echo "snapper config for apk-snap removed, ./snapshots subvol not removed."
    rm -f /etc/snapper/configs/root-apk-snap

elif [ -f "/etc/snapper/configs/root-apk-snap" ] && [ ! -d "/.snapshots" ]; then
    echo "snapper config for apk-snap removed, snapshots subvol does not exist."
    rm -f /etc/snapper/configs/root-apk-snap

elif [ -f "/etc/snapper/configs/root-apk-snap" ] || [ -d "/.snapshots" ]; then
    echo "snapper config for apk-snap does not exist, snapshots subvol not removed."

elif [ -f "/etc/snapper/configs/root-apk-snap" ] || [ ! -d "/.snapshots" ]; then
    echo "snapper config for apk-snap does not exist, snapshots subvol does not exist."
fi
